import {
	HEADER,
	TOKENNAME,
	HEADERPARAMS
} from '@/config/app';

export const BASE_URL = 'http://localhost:52601';

// TODO 芋艿：临时解决 uniapp 在小程序，undefined 会被 tostring 的问题
function deleteUndefinedProperties(obj) {
	for (let key in obj) {
		if (obj.hasOwnProperty(key)) {
			if (typeof obj[key] === 'object' && obj[key] !== null) {
				deleteUndefinedProperties(obj[key]); // 递归调用，处理嵌套的对象
			} else if (obj[key] === undefined) {
				delete obj[key];
			}
		}
	}
}

/**
 * 发送请求
 */
function baseRequest(url, method, data, {
    noVerify = false
  }, params) {
    let Url = BASE_URL,
      header = HEADER
    if (params != undefined) {
      header = HEADERPARAMS;
    }

	deleteUndefinedProperties(data)

	// 处理 token
	let token = uni.getStorageSync('token') || ''
	return new Promise((reslove, reject) => {
		console.log('BASE_URL:', BASE_URL)
		uni.request({
			url: `${BASE_URL}/${url}`, // TODO 芋艿：搞个 url 的配置
			method: method || 'GET',
			header: {
				"token": token
			},
			data: data || {},
			success: (res) => {
        // console.log("res2222-----",res);
				if (noVerify)
					reslove(res.data, res);
				else if (res.statusCode === 200 || res.data.code === 0)
					reslove(res.data, res);
		    else
					reject(res.data.msg || res.data.message || '系统错误');
			},
			fail: (msg) => {
				reject('请求失败');
			}
		})
	});
}

const request = {};

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
	request[method] = (api, data, opt, params) => baseRequest(api, method, data, opt || {}, params)
});



export default request;